<template>
  <div class="box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
      label-position="top"
    >
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="ruleForm.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
    </el-form>
    <a href="#register">还没有账号？立即注册>></a>
    <div style="text-align: center; margin-top: 20px">
      <el-button type="primary" @click="dl(ruleFormRef)">立即登录</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
export default {
  name: "",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const ruleFormRef = ref<FormInstance>();
    const data = reactive({
      ruleForm: {
        email: "2110410005@qq.com",
        password: "liu129499",
      },
    });

    const rules = reactive<FormRules>({
      email: [
        {
          required: true,
          message: "请输入邮箱地址",
          trigger: "blur",
        },
        {
          min: 3,
          max: 25,
          message: "长度在3-25之间",
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
          trigger: "blur",
        },
        {
          min: 3,
          max: 15,
          message: "长度在3-15之间",
          trigger: "blur",
        },
      ],
    });
    // 登陆
    const dl = async (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          store.dispatch("login", data.ruleForm).then((res) => {
            if (res.code == 0) {
              localStorage.setItem("token", res.data.token);
              ElMessage.success("登录成功");
              router.push("/");
            }
          });
          
        } else {
          console.log("error submit!", fields);
        }
      });
    };
    return {
      ...toRefs(data),
      rules,
      ruleFormRef,
      dl,
    };
  },
};
</script>

<style scoped lang='scss'>
.box {
  width: 300px;
  margin: 100px auto;
}
</style>